﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Linq;
using System.Web.Mvc;
using BLL;
using System.Collections.Generic;
using GameGo.Models;
using PagedList;
using Model;
using Newtonsoft.Json.Linq;
using GameGo.Attribute;
using System.Text.RegularExpressions;

namespace GameGo.Controllers
{
    public class StoreController : Controller
    {
        goodsBLL goodsContext = new goodsBLL();
        ordersBLL ordersContext = new ordersBLL();
        orderDetailBLL orderDetailContext = new orderDetailBLL();
        shopCarBLL shopCarContext = new shopCarBLL();
        usersBLL usersContext = new usersBLL();
        gameAccountBLL gameAccountContext = new gameAccountBLL();
        goodCommentBLL commentContext = new goodCommentBLL();
        // GET: Store
        /// <summary>
        /// 商品分类页
        /// </summary>
        /// <returns></returns>
        public ActionResult GoodsClassification()
        {
            return View();
        }
        /// <summary>
        /// 商品分页分部视图
        /// </summary>
        /// <param name="page"></param>
        /// <param name="type"></param>
        /// <param name="name"></param>
        /// <param name="orderType"></param>
        /// <returns></returns>
        public ActionResult GoodsClassificationPatialView(int? page, int type, string name = "undefined", int orderType = 0)
        {
            var pageSize = 20;
            var pageNumber = page ?? 1;
            IEnumerable<goods> list;
            if (name == "undefined")
            {
                list = goodsContext.GetGoodsByType(type, orderType: orderType);
            }
            else
            {
                list = goodsContext.GetGoodsByType(type, name: name, orderType: orderType);
            }
            IPagedList<goods> pagedList = list.ToPagedList(pageNumber, pageSize);
            return PartialView(pagedList);

        }
        public ActionResult SearchGoods(string name)
        {
            ViewBag.Name = name;
            return View("GoodsClassification");
        }
        /// <summary>
        /// 商品详情页入口
        /// </summary>
        /// <returns></returns>
        public ActionResult GoodDetails(int? id)
        {
            if (id == null) return View("GoodsClassification");
            var col = goodsContext.GetGoodsByID(id);
            return View(col);
        }
        public ActionResult RecommendPatialView()
        {
            var randoms = goodsContext.GetGoodsByRandom(10);
            return PartialView(randoms);
        }
        public ActionResult CommentPatialView(int? page, int id)
        {
            var pageSize = 20;
            var pageNumber = page ?? 1;
            var comments = commentContext.GetGoodCommentsByGoodId(id);
            IPagedList<goodComment> pagedList = comments.ToPagedList(pageNumber, pageSize);
            ViewBag.commentId = id;
            return PartialView(pagedList);
        }
        public ActionResult Orders(int GoodID, int num, int userid = 0)
        {
            if (userid == 0) return Content("<script>history.go(-1);alert(\"请先登录\")</script>");
            OrdersModel ordersModel = new OrdersModel();
            goods good = goodsContext.GetGoodsByID(GoodID);
            OrderModel sc = new OrderModel
            {
                UserID = userid,
                GoodID = good.ID,
                Name = good.goodName,
                GoodsNum = num,
                Price = good.goodprice,
                SumPrice = good.goodprice * num,
                GoodsImage = good.goodImage
            };
            List<OrderModel> shoppingCar = new List<OrderModel>();
            shoppingCar.Add(sc);
            ordersModel.OrderList = shoppingCar;
            ViewBag.State = 0;
            return View(ordersModel);
        }
        public ActionResult OrdersGameAccountPatialView(int uid)
        {
            var gAc = gameAccountContext.GetGameAccounts(uid);
            return PartialView(gAc);
        }
        public ActionResult GenerateOrder(string json, int userid = 0, int gameServer = 0, string playName = "")
        {
            List<OrderModel> orderModel = new List<OrderModel>();
            JObject obj = JObject.Parse(json);
            foreach (KeyValuePair<string, JToken> item in obj)
            {
                int num = 0, car = 0;
                int key = Convert.ToInt32(item.Key);
                goods good = goodsContext.GetGoodsByID(key);
                JObject value = (JObject)item.Value;

                foreach (KeyValuePair<string, JToken> data in value)
                {
                    if (data.Key == "num") { num = Convert.ToInt32(data.Value); }
                    else if (data.Key == "carid") { car = Convert.ToString(data.Value) != "" ? Convert.ToInt32(data.Value) : 0; }
                }
                if (num < 0) { num = 0; car = 0; }
                OrderModel ordersM = new OrderModel()
                {
                    ShoppingCarID = car,
                    GoodID = good.ID,
                    Name = good.goodName,
                    GoodsNum = num,
                    Price = good.goodprice,
                    SumPrice = good.goodprice * num,
                    GoodsImage = good.goodImage
                };
                orderModel.Add(ordersM);
            }
            orders ordersp = new orders()
            {
                userID = userid,
                goodNum = orderModel.Count(),
                sumPrice = orderModel.Sum(a => a.SumPrice),
                createTime = DateTime.Now,
                nowState = 0,
                payTime = DateTime.Now
            };
            ordersp.accountID = gameAccountContext.AddGameAccount(userid, gameServer, playName);
            ordersContext.AddOrders(ordersp);
            int oid = ordersContext.GetLastOrder(userid).ID;
            foreach (var item in orderModel)
            {
                orderDetail orderDetail = new orderDetail()
                {
                    orderId = oid,
                    goodId = item.GoodID,
                    goodNum = item.GoodsNum,
                    goodPrice = item.Price,
                    sumPrice = item.SumPrice
                };
                orderDetailContext.AddOrderDetail(orderDetail);
                if (item.ShoppingCarID != 0) shopCarContext.DeleteSingleShoppingCar(item.ShoppingCarID);
            }
            TempData["orderID"] = oid;
            ViewBag.OrderID = oid;
            return RedirectToAction("Payment");
        }
        public ActionResult Payment(int? id)
        {
            int orderid = id ?? Convert.ToInt32(TempData["orderID"]);
            TempData["orderID"] = orderid;
            //if ((string)Session["UserName"] == ordersBLL.GetModelByID(orderid).UserName)
            //{
            return View(ordersContext.GetOrderByID(orderid));
            //}
            //else return Content("<script>history.go(-1)</script>");
        }

        [HttpPost]
        public string Pay(int orderID, int userid)
        {
            orders order = ordersContext.GetOrderByID(orderID);
            order.nowState = 1;
            ordersContext.UpdateOrder(order);
            return "支付成功";
        }

        [HttpPost]
        public bool AddShoppingCar(int ID, int num, int uid = 0)
        {
            if (uid == 0) return false;
            if (shopCarContext.isExistGood(ID))
            {
                shopCar shoppingCar = shopCarContext.GetShopCarByIDAndUid(ID, uid);
                int sid = shoppingCar.ID;
                num += shoppingCar.goodNum;
                shopCarContext.UpdatteNum(shoppingCar.ID, num);
            }
            else shopCarContext.AddShoppingCar(ID, uid, num);
            return true;
        }
        [isAuthorize]
        public ActionResult ShoppingCar(int? uid)
        {
            int userid = Convert.ToInt32(Session["UserID"]);
            var sc = shopCarContext.GetShopCarByUid(userid);
            if (userid == 0) return Content("<script>history.go(-1);alert(\"请先登录\")</script>");
            return View(sc);
        }
        public void DeleteSingleShoppingCar(int id)
        {
            shopCarContext.DeleteSingleShoppingCar(id);
        }
        public void UpdateNum(int id, int num)
        {
            shopCarContext.UpdatteNum(id, num);
        }
        public void DeleteShoppingCars(string json)
        {
            JObject obj = JObject.Parse(json);
            foreach (KeyValuePair<string, JToken> item in obj)
            {
                int key = Convert.ToInt32(item.Key);
                shopCarContext.DeleteSingleShoppingCar(key);
            }
        }
        public ActionResult CarToPlaceOrder(string json)
        {
            ViewBag.Nav = "购物车";
            OrdersModel ordersModel = new OrdersModel();
            shopCar sc;
            List<OrderModel> shoppingCar = new List<OrderModel>();
            JObject obj = JObject.Parse(json);
            int? uid;
            foreach (KeyValuePair<string, JToken> item in obj)
            {
                int key = Convert.ToInt32(item.Key);
                sc = shopCarContext.GetShopCarByID(key);
                uid = sc.userID;
                OrderModel scm = new OrderModel()
                {
                    UserID = (int)uid,
                    ShoppingCarID = sc.ID,
                    GoodID = (int)sc.goodId,
                    Name = sc.goods.goodName,
                    GoodsNum = sc.goodNum,
                    Price = sc.goods.goodprice,
                    SumPrice = sc.goods.goodprice * sc.goodNum,
                    GoodsImage = sc.goods.goodImage
                };
                shoppingCar.Add(scm);
            }
            ordersModel.OrderList = shoppingCar;
            ViewBag.State = 0;
            return View("Orders", ordersModel);
        }
        [isAuthorize]
        public ActionResult PersonalCenter(int? uid)
        {
            int userid = uid ?? Convert.ToInt32(Session["UserID"]);
            var user = usersContext.GetUsersById((int)userid);
            return View(user);
        }
        public ActionResult MyOrdersPatialView(int uid = 1)
        {
            return PartialView(ordersContext.GetOrdersByUid(uid));
        }
        public ActionResult DetailToPlaceOrder(int orderID)
        {
            ViewBag.Nav = "查看订单";
            orders orders = ordersContext.GetOrderByID(orderID);
            ViewBag.state = orders.nowState;
            ViewBag.OrderID = orderID;
            OrdersModel placeOrderViewModel = new OrdersModel();
            List<OrderModel> shoppingCar = new List<OrderModel>();
            foreach (var item in orders.orderDetail)
            {
                OrderModel scm = new OrderModel()
                {
                    UserID = (int)orders.userID,
                    GoodID = (int)item.goodId,
                    Name = item.goods.goodName,
                    GoodsNum = item.goodNum,
                    Price = item.goods.goodprice,
                    SumPrice = item.goods.goodprice * item.goodNum,
                    GoodsImage = item.goods.goodImage
                };
                shoppingCar.Add(scm);
            }
            placeOrderViewModel.OrderList = shoppingCar;
            return View("Orders", placeOrderViewModel);
        }
        public ActionResult MyInformationPartialView(int? uid)
        {
            InfoModel  ac = new InfoModel();
            int userid = uid ?? Convert.ToInt32(Session["UserID"]);
            ac.gameac = gameAccountContext.GetGameAccounts(userid).FirstOrDefault();
            ac.user = usersContext.GetUsersById(userid);
            return PartialView(ac);
        }
        public ActionResult ConfirmReceive(int uid)
        {
            return PartialView(ordersContext.GetOrdersByUid(uid).Where(a=>a.nowState == 2));
        }
        public void Confirm(int orderid)
        {
            ordersContext.Confirm(orderid);
        }
        public ActionResult GameAccountPatialView(int uid)
        {
            return PartialView(gameAccountContext.GetGameAccounts(uid));
        }
        public ActionResult GoodReview(int uid)
        {
            var c = ordersContext.GetOrdersByUid(uid).Where(a => a.nowState == 3);
            return PartialView(c);
        }
        [isAuthorize]
        public ActionResult SendView(int id, int goodId)
        {
            goodComment sendView = new goodComment();
            sendView.userID = Convert.ToInt32(Session["UserID"]);
            sendView.oDId = id;
            sendView.goodId = goodId;
            return View(sendView);
        }
        [HttpPost]
        [ValidateInput(false)]
        [ValidateAntiForgeryToken]
        [isAuthorize]
        public ActionResult SendReply(goodComment sendView)
        {
            try
            {
                sendView.comTime = DateTime.Now;
                goodsContext.AddGoodsComment(sendView);
            }
            catch (Exception)
            {
                return Content("<script>alert('评论失败,请检查更改后重新评论！');history.go(-1);</script>");
            }
            return Content("<script>alert('评论成功！');window.location.href='../Store/PersonalCenter';</script>");
        }
        [isAuthorize]
        public ActionResult UploadPic(HttpPostedFileBase upload)
        {
            string result = string.Empty;
            var file = System.IO.Path.GetFileName(upload.FileName);
            string fileFormat = file.Split('.')[file.Split('.').Length - 1];
            Regex imageFormat = new Regex(@"^(bmp)|(png)|(gif)|(jpg)|(jpeg)");
            if (string.IsNullOrEmpty(file) || !imageFormat.IsMatch(fileFormat))
            {
                return Content("<script>alert('请上传正确格式的图片！')</script>");
            }
            else
            {
                string timeStamp = DateTime.Now.Ticks.ToString();
                string firstFileName = timeStamp.Substring(0, timeStamp.Length - 4);
                string imageStr = "Content/images/userUp/";
                string uploadPath = Server.MapPath("~/" + imageStr);
                string pictureFormat = file.Split('.')[file.Split('.').Length - 1];
                string fileName = firstFileName + "." + fileFormat;
                string saveFile = uploadPath + fileName;
                upload.SaveAs(saveFile);
                var url = "../../Content/images/userUp/" + fileName;
                var CKEditorFuncNum = System.Web.HttpContext.Current.Request["CKEditorFuncNum"];
                return Content("<script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + url + "\");</script>");
            }
        }
        public void UpdateUserName(int uid, string un)
        {
            if (un == "") return;
            usersContext.UpdateUserName(uid, un);
        }
        public void UpdateNickName(int uid, string un)
        {
            if (un == "") return;
            usersContext.UpdateNickName(uid, un);
        }
        public void UpdatePWD(int uid, string pwd)
        {
            if (pwd == "") return;
            usersContext.UpdatePWD(uid, pwd);
        }
        public void UpdateBirth(int uid, DateTime bt)
        {
            usersContext.UpdateBirth(uid, bt);
        }
        public void UpdateDec(int uid, string bt)
        {
            if (bt == "") return;
            usersContext.UpdateDec(uid, bt);
        }
        public void UpdatePlayName(int id,int b, string c)
        {
            if (b <= 0 || c == "") return;
            gameAccountContext.UpdateGameAC(id, b, c);
        }
        public void DeleteAc(int id)
        {
            gameAccountContext.RemoveGameAccount(id);
        }
        public int ADDAC(int uid, int a, string b)
        {
            return gameAccountContext.AddGameAccount(uid,a,b);
        }
    }
}